/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.reader;

import java.io.IOException;
import java.io.Reader;

public class LocateableReader extends Reader
{
	protected Reader delegate;

	private Location location = new Location();
	private Location markedLocation = null;
	private char lastCharacter;

	@Override
	public int read(char cbuf[], int off, int len) throws IOException
	{
		int amountRead = delegate.read(cbuf, off, len);
		char lastCharacter = this.lastCharacter;
		for (int i = 0; i < amountRead; i++)
		{
			char character = cbuf[i + off];
			if (character == '\r')
			{
				location.advanceLine();
			}
			else if (character == '\n' && lastCharacter != '\r')
			{
				location.advanceLine();
			}
			else if (character == '\t')
			{
				location.advanceColumnByTab();
			}
			else
			{
				location.advanceColumn();
			}
			lastCharacter = character;
		}
		this.lastCharacter = lastCharacter;
		return amountRead;
	}

	@Override
	public boolean markSupported()
	{
		return true;
	}

	@Override
	public void mark(int readAheadLimit) throws IOException
	{
		try
		{
			markedLocation = (Location) location.clone();
		}
		catch (CloneNotSupportedException e)
		{
			throw new IllegalStateException("Unexpected error while cloning location", e);
		}
		delegate.mark(readAheadLimit);
	}

	@Override
	public void reset() throws IOException
	{
		if (markedLocation != null)
		{
			location = markedLocation;
		}
		delegate.reset();
	}

	@Override
	public void close() throws IOException
	{
		delegate.close();
	}

	public Location getLocation()
	{
		try
        {
	        return (Location) location.clone();
        }
        catch (CloneNotSupportedException e)
        {
	        throw new IllegalStateException("Unexpected error while cloning location", e);
        }
	}

}
